package com.yinp.proapp.fragment.bottompage;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewbinding.ViewBinding;

import com.yinp.proapp.R;
import com.yinp.proapp.activity.LoginActivity;
import com.yinp.proapp.activity.bean.MyUserInfo;
import com.yinp.proapp.adapter.CommonAdapter;
import com.yinp.proapp.adapter.SingleViewHolder;
import com.yinp.proapp.base.fragment.AppBaseFragment;
import com.yinp.proapp.bean.SelectHeaderBean;
import com.yinp.proapp.constant.Constant;
import com.yinp.proapp.constant.SpConstants;
import com.yinp.proapp.databinding.DialogCenterInputBinding;
import com.yinp.proapp.databinding.DialogSelectHeaderBinding;
import com.yinp.proapp.databinding.FragmentMeBinding;
import com.yinp.proapp.databinding.ItemSelectHeaderBinding;
import com.yinp.proapp.module.task.activity.AddLabelActivity;
import com.yinp.proapp.utils.GlideUtils;
import com.yinp.proapp.utils.LoadUtils;
import com.yinp.proapp.utils.SelectTakePhoto;
import com.yinp.proapp.utils.SpUtils;
import com.yinp.tools.fragment_dialog.BaseDialogFragment;
import com.yinp.tools.fragment_dialog.CommonDialogFragment;
import com.yinp.tools.fragment_dialog.DialogFragmentHolder;
import com.yinp.tools.fragment_dialog.ViewConvertListener;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import io.rong.imlib.RongIMClient;

public class MeFragment extends AppBaseFragment<FragmentMeBinding> {
    private SelectTakePhoto selectTakePhoto;

    @Override
    protected void initViews(View view) {
        initClick(this, bd.ivHead, bd.sllAddLabel, bd.sllSetNetHeader, bd.sllSetNickName, bd.sllLoginOut);
        selectTakePhoto = new SelectTakePhoto();
        String img = SpUtils.getValue(SpConstants.HEAD_PICTURE, "");
        if (TextUtils.isEmpty(img)) {
            GlideUtils.intoRadius(getContext(), R.mipmap.default_head, bd.ivHead, 100);
        } else {
            GlideUtils.intoRadius(getContext(), img, bd.ivHead, 100, true);
        }
        if (MyUserInfo.isLogin()) {
            MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
            bd.tvNickName.setText(myUserInfo.getNickName());
        }
        login();
    }

    @Override
    public void onClick(View v) {
        if (v == bd.ivHead) {
            selectTakePhoto.selectType(MeFragment.this, 1);
        } else if (v == bd.sllAddLabel) {
            goToActivity(AddLabelActivity.class);
        } else if (v == bd.sllSetNetHeader) {//更改网络头像
            selectHeader();
        } else if (v == bd.sllSetNickName) {//设置更改昵称
            setNickNameDialog("设置昵称");
        } else if (v == bd.sllLoginOut) {
            //融云
            RongIMClient.getInstance().logout();
            MyUserInfo.logOut();
            getActivity().finish();
            //内部创建的Dialog持有了对MajorActivity的引用,需要置空
            LoadUtils.getInstance().setNull();
            goToActivity(LoginActivity.class);
        }
    }

    private void login() {
        MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
        RongIMClient.connect(myUserInfo.getToken(), 0, new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "onSuccess:im登录成功 ");
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {
                Log.d(TAG, "onError: im登录失败");
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {
                Log.d(TAG, "onDatabaseOpened: ");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (selectTakePhoto.type == Constant.TAKE_PHOTO) {
                GlideUtils.intoRadius(getContext(), selectTakePhoto.imageUri, bd.ivHead, 100, true);
                SpUtils.saveValue(selectTakePhoto.imageUri.toString(), SpConstants.HEAD_PICTURE);
            } else if (selectTakePhoto.type == Constant.SELECT_PHOTO) {
                if (data != null) {
                    String url = selectTakePhoto.handleImageOnKitKat(getContext(), data);
                    GlideUtils.intoRadius(getContext(), url, bd.ivHead, 100, true);
                    SpUtils.saveValue(url, SpConstants.HEAD_PICTURE);
                }
            }
        }
    }

    private List<SelectHeaderBean> selectHeaderList = new ArrayList<>();

    /**
     * 由于没有服务器只能暂时这样
     */
    public void selectHeader() {
        if (selectHeaderList.size() == 0) {
            selectHeaderList.add(new SelectHeaderBean("https://s3.bmp.ovh/imgs/2021/11/b11dac0fd9ceb10e_thumb.jpg"));
            selectHeaderList.add(new SelectHeaderBean("https://ftp.bmp.ovh/imgs/2019/08/ede01719f0e5c004_thumb.jpg"));
            selectHeaderList.add(new SelectHeaderBean("https://s3.bmp.ovh/imgs/2021/11/31200f89109b91a7.jpg"));
            selectHeaderList.add(new SelectHeaderBean("https://s3.bmp.ovh/imgs/2022/01/ed761bacb8c6f01b_thumb.jpg"));
        }
        CommonDialogFragment.newInstance().setLayout(DialogSelectHeaderBinding.inflate(getLayoutInflater()))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        DialogSelectHeaderBinding binding = (DialogSelectHeaderBinding) viewBinding;
                        CommonAdapter<SelectHeaderBean> selectHeaderAdapter = new CommonAdapter<SelectHeaderBean>(getContext(), selectHeaderList) {
                            @Override
                            protected SingleViewHolder setComViewHolder(View view, int viewType, ViewGroup parent) {
                                return new SingleViewHolder(ItemSelectHeaderBinding.inflate(mInflater, parent, false));
                            }

                            @Override
                            public void onBindItem(SingleViewHolder holder, int position, SelectHeaderBean item) {
                                ItemSelectHeaderBinding binding1 = (ItemSelectHeaderBinding) holder.getBinding();
                                GlideUtils.intoRadius(getContext(), item.getHeadUrl(), binding1.ivImg, R.mipmap.default1, 100);
                            }
                        };
                        selectHeaderAdapter.setOnItemClickListener((position, view) -> {
                            for (int i = 0; i < selectHeaderList.size(); i++) {
                                if (i != position && selectHeaderList.get(i).isSelect()) {
                                    selectHeaderList.get(i).setSelect(false);
                                }
                            }
                            selectHeaderList.get(position).setSelect(!selectHeaderList.get(position).isSelect());
                        });
                        binding.rvList.setLayoutManager(new GridLayoutManager(getContext(), 2));
                        binding.rvList.setHasFixedSize(true);
                        binding.rvList.setAdapter(selectHeaderAdapter);
                        binding.stvSure.setOnClickListener(v -> {
                            for (int i = 0; i < selectHeaderList.size(); i++) {
                                if (selectHeaderList.get(i).isSelect()) {
                                    String mUrl = selectHeaderList.get(i).getHeadUrl();
                                    GlideUtils.intoRadius(getContext(), mUrl, bd.ivHead, 100, true);
                                    /**
                                     * 设置bmob的头像
                                     */
                                    MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
                                    myUserInfo.setHeadUrl(selectHeaderList.get(i).getHeadUrl());
                                    myUserInfo.update(myUserInfo.getObjectId(), new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            SpUtils.saveValue(mUrl, SpConstants.HEAD_PICTURE);
                                            showToast("修改成功");
                                            Log.d(TAG, "头像添加成功");
                                        }
                                    });
                                    break;
                                }
                            }
                            dialogFragment.dismiss();
                        });
                    }
                }).setAnimStyle(R.style.BottomDialogAnimation).setGravity(BaseDialogFragment.BOTTOM).setPercentSize(0f, 0f)
                .show(getChildFragmentManager());
    }

    /**
     * 设置昵称
     */
    private void setNickNameDialog(String title) {
        CommonDialogFragment.newInstance().setLayout(DialogCenterInputBinding.inflate(getLayoutInflater()))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        DialogCenterInputBinding binding = (DialogCenterInputBinding) viewBinding;
                        binding.tvTitle.setText(title);
                        MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
                        binding.etNickName.setText(myUserInfo.getNickName());

                        binding.stvSure.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                            myUserInfo.setNickName(binding.etNickName.getText().toString());
                            myUserInfo.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        bd.tvNickName.setText(binding.etNickName.getText().toString());
                                        showToast("昵称修改成功");
                                    } else {
                                        showToast("昵称修改失败");
                                    }
                                }
                            });
                        });
                    }
                }).setAnimStyle(R.style.CenterDialogAnimation).setGravity(BaseDialogFragment.CENTER).setPercentSize(0.8f, 0f)
                .show(getChildFragmentManager());
    }
}
